<?php


namespace Xy\Rbac\Repositories;



use Xy\Rbac\Models\RbacPowerPageModel;

class RbacPowerPageRepository extends BaseRepository {
    public $eloquentClassName = RbacPowerPageModel::class;
    
    /**
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAllPowerPage($queryExtDealFn = null) {
        $query = $this->_eloquent->newQuery()->orderBy('order');
        
        is_callable($queryExtDealFn) && call_user_func_array($queryExtDealFn, [$query]);
        
        return $query->get();
    }
    
    /**
     * @param array $idList
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getPowerPageByIdList(array $idList, $queryExtDealFn = null) {
        $query = $this->_eloquent->newQuery()
            ->whereIn('id', $idList)
            ->where('status', RbacPowerPageModel::STATUS_YES);
        
        is_callable($queryExtDealFn) && call_user_func_array($queryExtDealFn, [$query]);
        
        return $query->get();
    }
    
    /**
     * @param array $dataInfo
     * @param array $fillAble
     *
     * @return RbacPowerPageModel
     */
    public function storePowerPage(array $dataInfo, array $fillAble) {
        /** @var RbacPowerPageModel $newItem */
        $newItem = $this->_eloquent->newInstance();
        $newItem->fillable($fillAble)->fill($dataInfo);
        $newItem->save();
        
        return $newItem;
    }
    
    /**
     * @param $id
     *
     * @return array
     */
    public function destroyPowerPage($id) {
        $this->_eloquent->newQuery()->find($id)->delete();
        
        return [];
    }
    
    /**
     * @param $id
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getChildrenByPid($pid) {
        return $this->_eloquent->newQuery()
            ->where('pid', $pid)
            ->get();
    }
    
    /**
     * @param $id
     * @param $dataInfo
     * @param $fillAble
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     * @throws \Exception
     */
    public function updatePowerPageById($id, $dataInfo, $fillAble) {
        $updateItem = $this->_eloquent->newQuery()->find($id);
        if ($updateItem) {
            $updateItem->fillable($fillAble)->fill($dataInfo)->save();
        } else {
            throw new \Exception('条目不存在');
        }
        
        return $updateItem;
    }
}